package com.hongawen.poi.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.util.CharsetUtil;
import com.hongawen.poi.pojo.Course;
import com.hongawen.poi.pojo.Student;
import com.hongawen.poi.pojo.Teacher;
import com.hongawen.poi.util.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年03月30日 19:26
 */
@Slf4j
@Service
public class MultipleService {

    private static List<Map<String,Object>> list = new ArrayList<>();

    private static List<Student> students = new ArrayList<>();
    private static List<Teacher> teachers = new ArrayList<>();

    static {
        Student student;
        for (int i = 1; i < 6; i++) {
            student = new Student();
            student.setName("小明" + i + "号");
            student.setBirthday(new Date());
            student.setRegistrationDate(LocalDateTime.now());
            student.setSex(i % 2);
            students.add(student);
        }

        Teacher teacher;
        for (int i = 1; i < 4; i++) {
            teacher = new Teacher();
            teacher.setName("小王老师" + i + "号");
            teacher.setAge(35 + i);
            teachers.add(teacher);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("title",new ExportParams("教师","教师"));
        map.put("entity",Teacher.class);
        map.put("data",teachers);

        list.add(map);

        Map<String,Object> map1 = new HashMap<>();
        map1.put("title",new ExportParams("学生","学生"));
        map1.put("entity",Student.class);
        map1.put("data",students);
        list.add(map1);

    }


    public void exportMultiple() {
        try {
            HttpServletResponse response = HttpServletUtil.getResponse();
            String fileName = URLEncoder.encode("hello.xls", CharsetUtil.UTF_8);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            ServletOutputStream outputStream = response.getOutputStream();
            Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            log.error(">>> 导出数据异常：{}", e.getMessage());
        }
    }



}
